package com.only4play.practice.invoice.core.envents;

import com.only4play.practice.invoice.api.model.OrderRegisterResultModel;
import com.only4play.practice.invoice.core.entity.OrderReceipt;
import com.only4play.practice.invoice.core.entity.ReceiptItem;
import com.only4play.practice.invoice.core.service.IReceiptItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderReceiptEventProcessor {

  private final IReceiptItemService receiptItemService;

//  private final OrderReceiptDocumentRepository orderReceiptDocumentRepository;


  /**
   * 保存到ES  CQRS架构，解决各个维度的订单查询问题
   * @param orderRegisterEvent
   */
  @EventListener
  public void handleOrderRegisterEventForEs(OrderReceiptEvents.OrderRegisterEvent orderRegisterEvent){

    OrderReceipt orderReceipt = orderRegisterEvent.getOrderReceipt();
//    OrderReceiptDocument document = OrderReceiptMapper.INSTANCE.entity2Document(
//        orderReceipt);
//    //id 不用数据库id,用唯一流水号
//    document.setId(String.valueOf(orderReceipt.getRegisterFlowNo()));
//    document.setResultItems(orderRegisterEvent.getRegisterResultModel().getItems());
//    orderReceiptDocumentRepository.save(document);
  }

  /**
   * 保存凭据项
   * 这里呢，可以写个批量，也可以独立存，看需求，一般订单项不会太多foreach 就行了
   */
  @EventListener
  public void handleRegisterEventForItem(OrderReceiptEvents.OrderRegisterEvent orderRegisterEvent){
        List<OrderRegisterResultModel.ResultItem> items = orderRegisterEvent.getRegisterResultModel().getItems();
        List<ReceiptItem> creators = items.stream().map(
                item -> ReceiptItem.builder()
            .receiptId(orderRegisterEvent.getOrderReceipt().getId())
            .skuId(String.valueOf(item.getSkuId()))
            .skuName(item.getSkuName())
            .taxCategory(item.getTaxCategory())
            .taxCategoryCode(item.getTaxCategoryCode())
            .taxRate(item.getTaxRate())
            .amount(item.getAmount())
            .count(item.getCount())
            .build()
        ).collect(Collectors.toList());
        // receiptItemService.saveBatch(creators);
      }

}
